<template>
  <cu-layout ref="layoutRef" one-page title="购物车" tabbar="/pages/cart/index">
    <view class="h-full flex-v ">
      <view class="py-12 px-15 leading-20 bg-white hair-b">
        <view class="flex-ba">
          <view class="">共 <text class="font-bold text-primary text-16">{{ list.length }}</text> 件商品</view>
          <view class="" @click="state.isEdit = !state.isEdit">{{ state.isEdit ? '完成' : '管理' }}</view>
        </view>
      </view>
      <view class="flex-1 overflow-scroll">
        <scroll-view class="p-10 border-box">
          <view class="bg-white rounded-6 overflow-hidden">
            <view v-show="!list.length" class="py-40">
              <uv-empty mode="car" />
            </view>
            <view v-for="(item, i) in list" :key="item.id" class="item flex-a py-12 px-14">
              <text class="iconfont check-icon" :class="state.selected.includes(item.id) ? 'icon-yuanxingxuanzhongfill' : 'icon-yuanxingweixuanzhong'" @click.stop="onCheckboxChange(item.id)" />
              <view class="flex-1 ml-10">
                <view class="flex">
                  <view class="flex-shrink rounded-4 overflow-hidden mr-10" @click="$.router.go('/pages/goods/detail', {id: item.product_id})">
                    <image class="block" :style="$.utils.getSize(80)" :src="item.sku_logo" mode="" />
                  </view>
                  <view class="flex-1 flex-vb">
                    <view class="" @click="$.router.go('/pages/goods/detail', {id: item.product_id})">
                      <view class="ellipsis-2 text-15">{{ item.product_name }}</view>
                      <view class="ellipsis-1 text-13 text-tips my-5">{{ item.sku_name }}</view>
                    </view>
                    <view class="flex-b">
                      <cu-price class="text-primary" :value="item.retail_price" />
                      <view class="">
                        <uv-number-box
                          :decimal-length="2"
                          input-format-disabled
                          :min="0"
                          :max="20"
                          :input-width="50"
                          :button-size="24"
                          :model-value="item.num"
                          async-change
                          @change="({value})=> onNumChange(value, i)"
                        />
                      </view>
                    </view>
                  </view>
                </view>
                <view class="mt-10 flex leading-20 ">
                  <view class="flex-shrink text-tips">备注:</view>
                  <view class="flex-1 ellipsis-2 px-10 text-content">{{ item.remark }}</view>
                  <view class="iconfont icon-xiugai text-primary" @click.stop="openRemark(item)" />
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <view class="flex-ba h-50 px-12 bg-fa hair-t">
        <view class="h-24 flex-a" @click="onCheckboxChange">
          <view class="iconfont check-icon" :class="state.selected.length && list.length === state.selected.length ? 'icon-yuanxingxuanzhongfill' : 'icon-yuanxingweixuanzhong'" />
          <view class="ml-8">全选</view>
        </view>
        <view class="pl-20">
          <view v-show="!state.isEdit" class="flex-a">
            <view class="leading-20">
              <view class="">总计：<cu-price class="text-primary" :value="total" /></view>
            </view>
            <view class="ml-20">
              <uv-button shape="circle" type="primary" :disabled="state.selected.length === 0" :color="`linear-gradient(to right, ${$.color.primary}, ${$.color.primaryDark})`" @click="save">
                <view class="px-7 flex-a"><view class="">去下单</view><view class="ml-3">({{ state.selected.length }})</view></view>
              </uv-button>
            </view>
          </view>
          <view v-show="state.isEdit" class="flex-a">
            <view class="">
              <uv-button
                plain
                shape="circle"
                :disabled="state.selected.length === 0"
                type="primary"
                size="small"
                text="收藏"
                @click="collect"
              />
            </view>
            <view class="ml-10">
              <uv-button
                plain
                shape="circle"
                :disabled="state.selected.length === 0"
                type="error"
                size="small"
                text="删除"
                @click="remove"
              />
            </view>
          </view>
        </view>
      </view>
    </view>
    <cu-cart-remark v-model:show="remark.show" :text="remark.text" :current="remark.id" @done="remarkDone" />
  </cu-layout>
</template>

<script setup>
import {
  computed,
  ref,
  reactive
} from 'vue'
import {
  onLoad,
  onShow
} from '@dcloudio/uni-app'
import $ from '@/sheep'
const layoutRef = ref()
const state = reactive({
  list: [],
  selected: [],
  checked: false,
  isEdit: false,
  loading: false
})

const remark = reactive({
  id: 0,
  show: false,
  text: ''
})

const list = computed(() => $.store('shop').cartList)

const total = computed(() => $.utils.sum(list.value.filter(v => state.selected.includes(v.id)), 'amount'))
onLoad(() => {})

onShow(async() => {
  await $.store('shop').isReady
  relaod()
})

function openRemark(data) {
  remark.id = data.id
  remark.text = data.remark
  remark.show = true
}

function remarkDone(data) {
  const index = list.value.findIndex(v => v.id === data.id)
  list.value[index].remark = data.remark
}

function checkLoading() {
  if (state.loading || !state.selected.length) {
    return false
  } else {
    state.loading = true
    return true
  }
}

function save() {
  if (checkLoading()) {
    $.post('/Store/preSubmitOrder', { ids: state.selected }).then(res => {
      if (res.success) {
        $.router.go('/pages/order/confirm', { ids: state.selected.join(',') })
      } else {
        $.utils.showModal({
          showCancel: false,
          content: res.msg
        }).then(() => {})
      }
    }).finally(() => state.loading = false)
  }
}

function relaod() {
  $.store('shop').cartLoad().then(list => {
    if (state.selected.length) {
      const ids = list.map(v => v.id)
      state.selected = state.selected.filter(t => ids.includes(t))
    }
    if (!list.length) state.isEdit = false
  })
}

function remove() {
  if (checkLoading()) {
    $.post('/Store/deleteCart', { ids: state.selected }).then(res => {
      $.utils.toast(res.msg)
      res.success && relaod()
    }).finally(() => state.loading = false)
  }
}

function onNumChange(num, index) {
  $.debounce(() => {
    num = num > 0 ? num : 0
    const id = list.value[index].id
    $.post('/Store/editCart', { id, num }).then(res => {
      if (res.success) {
        relaod()
      } else {
        $.utils.toast(res.msg)
      }
    })
  }, 100)
}

function collect() {
  if (checkLoading()) {
    $.post('/Store/collectCart', { ids: state.selected }).then(res => {
      $.utils.toast(res.msg)
      res.success && relaod()
    }).finally(() => state.loading = false)
  }
}

function onCheckboxChange(id) {
  if (id > 0) {
    const index = state.selected.indexOf(id)
    if (index === -1) {
      state.selected.push(id)
    } else {
      state.selected.splice(index, 1)
    }
  } else {
    state.selected = list.value.length === state.selected.length ? [] : list.value.map(v => v.id)
  }
}

</script>
<style lang="scss">
.check-icon {
	font-size: 44rpx;
	color: $uv-tips-color;
	&.icon-yuanxingxuanzhongfill {
		color: $uv-primary;
	}
}
.item {
	position: relative;
	&:not(:last-child)::after {
		content: '';
		position: absolute;
		right: 0;
		bottom: 0;
		width: calc(100% - 90rpx);
		height: 1rpx;
		border-bottom: 1rpx solid #eee;
	}
	::v-deep {
		.u-number-box__plus, .u-number-box__minus {
			width: 30px;
		}
	}

}

</style>
